package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.constant.insure.InsureConstant;
import com.itheima.sfbx.framework.commons.dto.basic.TreeItemVO;
import com.itheima.sfbx.framework.commons.dto.basic.TreeVO;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.NoProcessing;
import com.itheima.sfbx.insurance.dto.CategoryVO;
import com.itheima.sfbx.insurance.mapper.CategoryMapper;
import com.itheima.sfbx.insurance.pojo.Category;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description：保险分类服务实现类
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    ICategoryConditionService categoryConditionService;

    @Autowired
    ICategoryCoefficentService categoryCoefficentService;

    @Autowired
    ICategorySafeguardService categorySafeguardService;


    @Override
    public Page<CategoryVO> findPage(CategoryVO categoryVO, int pageNum, int pageSize) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public CategoryVO save(CategoryVO categoryVO) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public Boolean update(CategoryVO categoryVO) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //TODO
        return null;
    }

    @Override
    public List<CategoryVO> findList(CategoryVO categoryVO) {
        return null;
    }



    @Override
    public TreeVO categoryTreeVO(String parentCategoryNo, String categoryType,String[] checkedCategoryNos) {
        String rootNo = StrUtil.isBlank(parentCategoryNo)?SuperConstant.ROOT_PARENT_ID:parentCategoryNo;
        List<Category> list = this.lambdaQuery()
                .likeRight(Category::getCategoryNo, NoProcessing.processString(rootNo))
                .eq(Category::getDataState, SuperConstant.DATA_STATE_0)
                .eq(StrUtil.isNotBlank(categoryType), Category::getCategoryType, categoryType)
                .list();
        List<String> checkedCategoryList = new ArrayList<>();
        if(checkedCategoryNos != null){
            checkedCategoryList.addAll(Arrays.asList(checkedCategoryNos));
        }
        if (CollUtil.isEmpty(list))     {
            return null;
        }
        TreeVO treeVO = new TreeVO();
        //把categoryList转成需要的ItemVO
        List<TreeItemVO> voList = list.stream().map(ca->{
            TreeItemVO vo = new TreeItemVO();
            vo.setId(ca.getCategoryNo());
            vo.setLabel(ca.getCategoryName());
            vo.setParentId(ca.getParentCategoryNo());
            vo.setIsChecked(checkedCategoryList.contains(ca.getCategoryNo()));
            return vo;
        }).collect(Collectors.toList());
        //根据父ID把每个的children聚合起来
        Map<String, List<TreeItemVO>> parentMap = voList.stream().collect(Collectors.groupingBy(TreeItemVO::getParentId));
        //遍历每个元素，把有children的配上去
        for (TreeItemVO vo : voList) {
            List<TreeItemVO> children = parentMap.get(vo.getId());
            vo.setChildren(children);
        }
        //根据根节点把剩余的item装进去，里面的元素已经关联好了
        treeVO.setItems(parentMap.get(rootNo));
        return treeVO;
    }

    @Override
    public String createCategoryNo(String parentCategoryNo) {
        CategoryVO categoryVO = CategoryVO.builder()
            .parentCategoryNo(parentCategoryNo)
            .build();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Category::getParentCategoryNo,parentCategoryNo);
        List<Category> categoryList = list(queryWrapper);
        //无下属节点则创建下属节点
        if (EmptyUtil.isNullOrEmpty(categoryList)){
            return NoProcessing.createNo(parentCategoryNo,false);
        //有下属节点则累加下属节点
        }else {
            Long categoryNo = categoryList.stream()
                .map(category -> { return Long.valueOf(category.getCategoryNo());})
                .max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(categoryNo),true);
        }
    }

    /**
     * 人种榜险种榜分类
      * @param type
     */
    @Override
    public List<CategoryVO> categoryCheckRule(String type) {
        //判断是否是险种榜
        if(InsureConstant.checkIsInsureType(type)){
            List<CategoryVO> res = new ArrayList<>();
            //获取所有的险种榜
            List<String> allCheckRule = InsureConstant.getAllCheckRule();
            allCheckRule.forEach(e->{
                CategoryVO categoryVO = CategoryVO.builder().categoryNo(e).categoryName(InsureConstant.getRuleNameById(e)).build();
                res.add(categoryVO);
            });
            return res;
        }else{
            //说明是人种榜
            List<String> categoryNames = Arrays.asList("成年人", "少儿", "老人");
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Category::getCategoryName,categoryNames);
            queryWrapper.eq(Category::getDataState,SuperConstant.DATA_STATE_0);
            List<CategoryVO> res = BeanConv.toBeanList(list(queryWrapper), CategoryVO.class);
            return res;
        }
    }
}
